package com.example.seabedmusic.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.seabedmusic.R;
import com.example.seabedmusic.entity.HotSong;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.views.HotMusicPlayerActivity;

import java.util.ArrayList;
import java.util.List;

public class SongAdapter extends RecyclerView.Adapter<SongAdapter.ViewHolder> {

    private List<Song> songList;

    public SongAdapter(List<Song> songList) {
        this.songList = songList != null ? songList : new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_song, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (songList == null || position < 0 || position >= songList.size()) {
            return;
        }

        Song song = songList.get(position);
        if (song == null) {
            return;
        }

        // 设置歌曲信息 - 添加空值检查
        if (holder.songNameTv != null) {
            holder.songNameTv.setText(song.getTitle() != null ? song.getTitle() : "未知歌曲");
        }

        if (holder.artistTv != null) {
            holder.artistTv.setText(song.getArtist() != null ? song.getArtist() : "未知歌手");
        }

        // 加载封面
        if (holder.coverIv != null) {
            if (song.getCover() != null && !song.getCover().isEmpty()) {
                Glide.with(holder.itemView.getContext())
                        .load(song.getCover())
                        .placeholder(R.drawable.ic_music_note)
                        .error(R.drawable.ic_music_note)
                        .into(holder.coverIv);
            } else {
                holder.coverIv.setImageResource(R.drawable.ic_music_note);
            }
        }

        // 点击事件 - 播放（修改为与热歌榜相同的逻辑）
        holder.itemView.setOnClickListener(v -> {
            // 创建Intent跳转到热歌播放页面（统一使用HotMusicPlayerActivity）
            Intent intent = new Intent(holder.itemView.getContext(), HotMusicPlayerActivity.class);

            // 传递当前歌曲数据（转换为HotMusicPlayerActivity需要的格式）
            intent.putExtra("song_title", song.getTitle() != null ? song.getTitle() : "未知歌曲");
            intent.putExtra("song_artist", song.getArtist() != null ? song.getArtist() : "未知歌手");
            intent.putExtra("song_cover", song.getCover());
            intent.putExtra("song_album", song.getAlbum() != null ? song.getAlbum() : "未知专辑");
            intent.putExtra("song_hash", song.getId() != null ? song.getId() : "");
            intent.putExtra("song_rank", 0); // 普通歌曲没有排名，设为0

            // 传递当前位置和整个歌曲列表（转换为HotSong格式）
            intent.putExtra("current_position", position);

            // 将Song列表转换为HotSong列表传递
            ArrayList<HotSong> hotSongList = convertToHotSongList(songList);
            intent.putParcelableArrayListExtra("hot_song_list", hotSongList);

            // 启动热歌播放页面
            holder.itemView.getContext().startActivity(intent);
        });
    }

    /**
     * 将Song列表转换为HotSong列表
     */
    private ArrayList<HotSong> convertToHotSongList(List<Song> songs) {
        ArrayList<HotSong> hotSongs = new ArrayList<>();
        if (songs == null) {
            return hotSongs;
        }

        for (int i = 0; i < songs.size(); i++) {
            Song song = songs.get(i);
            if (song == null) {
                continue;
            }

            HotSong hotSong = new HotSong();

            hotSong.setId(song.getId());
            hotSong.setName(song.getTitle() != null ? song.getTitle() : "未知歌曲");
            hotSong.setAuthor(song.getArtist() != null ? song.getArtist() : "未知歌手");
            hotSong.setCover(song.getCover());
            hotSong.setAlbum(song.getAlbum() != null ? song.getAlbum() : "未知专辑");
            hotSong.setHash(song.getId() != null ? song.getId() : ""); // 使用ID作为hash
            hotSong.setRank(i + 1); // 设置排名

            hotSongs.add(hotSong);
        }
        return hotSongs;
    }

    @Override
    public int getItemCount() {
        return songList != null ? songList.size() : 0;
    }

    /**
     * 更新数据
     */
    public void updateData(List<Song> newSongs) {
        this.songList = newSongs != null ? newSongs : new ArrayList<>();
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView coverIv;
        TextView songNameTv;
        TextView artistTv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // 确保使用正确的ID
            coverIv = itemView.findViewById(R.id.cover_iv);
            songNameTv = itemView.findViewById(R.id.song_name_tv);
            artistTv = itemView.findViewById(R.id.artist_tv);

            // 调试日志
            if (coverIv == null) {
                android.util.Log.e("SongAdapter", "coverIv is null - check item_song layout");
            }
            if (songNameTv == null) {
                android.util.Log.e("SongAdapter", "songNameTv is null - check item_song layout");
            }
            if (artistTv == null) {
                android.util.Log.e("SongAdapter", "artistTv is null - check item_song layout");
            }
        }
    }
}